<template lang="pug">
  .CreateNodeModal
    Modal(
      v-model="isShowCreateNodeModal"
      :title="isCreate ? '新增环节' : '修改环节'"
      class-name="vertical-center-modal"
      width="480"
    )
      Form.ivu-row.has-rules-item2(ref="formData" :model="formData" :rules="rules" :label-width="160")
        FormItem.form-item.ivu-col(v-for="(item, index) of setFormItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop" v-show="item.isShow")
          template(v-if="item.type === 'input'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled")
          template(v-if="item.type === 'select'")
            Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled" @on-change="listenCall(item.fn, formData[item.model])")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.text}}
            Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled")
              Option(v-for="(c_item, c_index) of arrListDown[item.options]" :key="c_index" :value="c_item.value") {{c_item.text}}
          template(v-if="item.type === 'switch'")
            i-switch(v-model="formData[item.model]")
          template(v-if="item.type === 'radio'")
            RadioGroup.top-3-fu.relative(v-model="formData[item.model]" @on-change="listenCall(item.fn, item.model, $event)")
              Radio.display-inline-block(v-for="(c_item, index) of arrListDown[item.options]" :key="index" :label="+c_item.value") {{c_item.label}}
          template(v-if="item.type === 'textarea'")
            Input(v-model="formData[item.model]" :placeholder="item.placeholder" type="textarea" :rows="3")
          template(v-if="item.type === 'datePicker'")
            DatePicker.w-100(v-model="formData[item.model]" :placeholder="item.placeholder" type="date")
      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="handleSave()" :loading="!isCanSubmit") 保存
</template>

<script>
import { Common } from '@/utils/common.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
export default {
  name: 'CreateNodeModal',

  watch: {
  },

  computed: {
    setFormItem () {
      if (!this.isCreate) { // 编辑
        this.formItem[0].isShow = false
        this.formItem[0].isDisabled = true
        this.formItem[1].isDisabled = true
      } else {
        this.formItem[0].isShow = true
        this.formItem[0].isDisabled = false
        this.formItem[1].isDisabled = false
      }
      return this.formItem
    }
  },

  data () {
    return {
      positionId: '',
      isShowCreateNodeModal: false,
      isCreate: true,
      // createNodeModalTitle: '',
      parameterID: '',
      // treatmentEnjoyID: '',
      formData: {
        id: null,
        // parameterID: null,
        linkSort: null,
        parameterStatus: null,
        rowVersion: null,
        treatmentParameterLinkID: null,
        linkName: null,
        linkDescription: null,
        ifInsideEmployee: 1,
        principal: null,
        expectCompletionTime: null
      },
      formItem: [
        { type: 'select', label: '选择环节：', placeholder: '请选择环节', prop: 'treatmentParameterLinkID', model: 'treatmentParameterLinkID', style: 'ivu-col-span-24', options: 'treatmentParameterList', fn: 'treatmentParameterOnChange', isDisabled: false, isShow: true },
        { type: 'input', label: '环节：', placeholder: '请输入环节名称', prop: 'linkName', model: 'linkName', style: 'ivu-col-span-24', isDisabled: false, isShow: true },
        { type: 'textarea', label: '环节说明：', placeholder: '请输入环节说明', prop: 'linkDescription', model: 'linkDescription', style: 'ivu-col-span-24', isDisabled: false, isShow: true },
        { type: 'radio', label: '内部员工：', placeholder: '', prop: 'ifInsideEmployee', model: 'ifInsideEmployee', style: 'ivu-col-span-24', options: 'defaultRadioArr', isDisabled: false, isShow: true, fn: 'ifInsideEmployeeChange' },
        { type: 'input', label: '负责人：', placeholder: '', prop: 'principalName', model: 'principalName', style: 'ivu-col-span-24', options: 'principalName', isDisabled: false, isShow: true },
        { type: 'datePicker', label: '预计完成日期：', placeholder: '', prop: 'expectCompletionTime', model: 'expectCompletionTime', style: 'ivu-col-span-24', options: 'parameterstatus', isDisabled: false, isShow: true },
      ],
      rules: {
        // treatmentParameterLinkID: [
        //   { required: true, message: '请选择环节', trigger: 'change' }
        // ],
        linkName: [
          { required: true, message: '请输入环节名称', trigger: 'change' }
        ],
        linkDescription: [
          { required: true, message: '请输入环节说明', trigger: 'change' }
        ],
        // principal: [
        //   { required: true, message: '请选择负责人', trigger: 'change' }
        // ],
        expectCompletionTime: [
          { required: true, message: '请选择预计完成日期', type: 'date', trigger: 'change' }
        ]
      },
      arrListDown: {
        defaultRadioArr: [{ value: '1', label: '是' }, { value: '0', label: '否' }],
        parametertype: [],
        parameterstatus: [],
        principalNameList: [],
        treatmentParameterList: []
      },
      isCanSubmit: true,
      treatmentParameterListInit: []
    }
  },

  mounted () {
    this.positionId = JSON.parse(localStorage.getItem('clientLoginInfo')).data.positionId
    this.getEnum()
    this.getUserList()
    // this.getTreatmentParameterList()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典
    getEnum () {
      let groupName = 'treatment.parametertype,treatment.parameterstatus'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 获取待遇环节列表下拉
    async getTreatmentParameterList (id) {
      this.isCanSubmit = true
      this.treatmentParameterListInit = []
      this.arrListDown.treatmentParameterList = []
      var params = {
        treatmentEnjoyId: id,
        securityType: 1 // 社保=1，公积金=2，商保=3
      }
      let res = await TreatmentApi.getTreatmentParametersNotQuoteEnableList(params)
      console.log('获取待遇环节列表下拉 res: ', res)
      // this.arrListDown.treatmentParameterList = res.data.data
      
      if (res.data.success) {
        this.treatmentParameterListInit = res.data.data
        res.data.data.map(item => {
          this.arrListDown.treatmentParameterList.push({text: item.linkName, value: item.id})
        })
        this.show()
        // this.isShowCreateNodeModal = true
        // if (!this.isCreate) {
        //   this.isShowCreateNodeModal = true
        // } else {
        //   Object.keys(this.formData).forEach(key => {
        //     this.formData[key] = ''
        //   })
        // }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
      // console.log('this.arrListDown: ', this.arrListDown)
    },

    treatmentParameterOnChange (value) {
      var selectObj = this.treatmentParameterListInit.find(item => {
        return item.id === value
      })
      console.log('❤ selectObj: ', selectObj)
      this.formData.treatmentParameterLinkID = selectObj.id
      this.formData.linkName = selectObj.linkName
      this.formData.linkDescription = selectObj.linkDescription
      this.formData.linkSort = selectObj.linkSort
    },

    // 获取员工下拉
    async getUserList () {
      var params = {
        // department_id: this.positionId,
        GetRoleName: true,
        HasPaging: true,
        PowerType: 3,
      }
      let res = await TreatmentApi.getUserList(params)
      console.log('获取员工下拉 res: ', res)
      this.arrListDown.principalNameList = []
      if (res.data.success) {
        res.data.data.map(item => {
          this.arrListDown.principalNameList.push({text: item.name, value: item.id}) 
        })
      }
      console.log('this.arrListDown: ', this.arrListDown)
    },

    cancel () {
      this.isShowCreateNodeModal = false
      this.$refs.formData.resetFields()
    },

    show () {
      this.$refs.formData.resetFields()
      this.isCanSubmit = true
      this.isShowCreateNodeModal = true
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = ''
      })
      console.log('this.formData: ', this.formData)
    },

    // 根据ID获取参数环节
    async getModel (id) {
      console.log('id: ', id)
      let res = await TreatmentApi.getTreatmentEnjoyLink({TreatmentEnjoyLinkId: id})
      console.log('根据ID获取参数环节: ', res)
      if (res.status === 200 && res.data.success) {
        var data = res.data.data
        Object.keys(this.formData).forEach(key => {
          if (['ifInsideEmployee'].indexOf(key) !== -1) {
            this.formData[key] = +data[key]
          } else if (['linkSort'].indexOf(key) !== -1) {
            this.formData[key] = data[key] == 0 ? '1' : data[key]
          } else if (['expectCompletionTime'].indexOf(key) !== -1) {
            this.formData[key] = data[key] == '' ? new Date() : this.$moment(data[key]).format('YYYY-MM-DD')
          }else {
            this.formData[key] = data[key] + '' && data[key] + '' !== 'null' ? data[key] + '' : ''
          }
          // this.formData[key] = data[key] + '' && data[key] + '' !== 'null' ? data[key] + '' : ''
        })

        if (+this.formData.ifInsideEmployee == 0) {
          this.formItem[4].style = 'ivu-col-span-24 remove-required'
          this.formItem[4].isDisabled = true
        } else {
          this.formItem[4].style = 'ivu-col-span-24 is-required'
          this.formItem[4].isDisabled = false
        }
      } else {
      }
      // this.formData.expectCompletionTime = new Date()
    },

    // 保存
    async handleSave () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (+this.formData.ifInsideEmployee == 1 && !this.formData.principal) {
            this.$Message.warning('内部员工选择为“是”时，内部员工为必填')
          } else {
            this.isCanSubmit = false
            var params = {TreatmentEnjoyID: this.parameterID, SecurityType: 1, expectCompletionTime: this.$moment(this.formData.expectCompletionTime).format('YYYY-MM-DD')}
            console.log('保存params: ', {...this.formData, ...params})
            TreatmentApi.saveTreatmentEnjoyLink({...this.formData, ...params}).then(res => {
              console.log('保存: ', res)
              if (res.status === 200 && res.data.success) {
                this.$Message.success(res.data.message)
                this.cancel()
                this.$emit('query')
              } else {
                this.isCanSubmit = true
                this.$Message.error({
                  content: res.data.message,
                  duration: 10,
                  closable: true
                })
              }
            })
          }
          // this.cancel()
        }
      })
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formData[model] = value
    },

    ifInsideEmployeeChange (model, value) {
      console.log('model: ', model, ', value: ', value)
      this.formData[model] = value

      if (value == 0) {
        this.formData.principal = null
        this.formItem[4].isDisabled = true
        this.formItem[4].style = 'ivu-col-span-24 remove-required'
      } else {
        this.formItem[4].isDisabled = false
        this.formItem[4].style = 'ivu-col-span-24 is-required'
      }
    },
  }
}
</script>

<style lang="less" scoped>

</style>
